using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

namespace Web.Ajax.Controls
{
	[ToolboxData("<{0}:Tab runat=\"server\" Title=\"Tab Title\"></{0}:Tab>")]
	[ControlBuilderAttribute(typeof(ControlBuilder))]
	[ParseChildren(false)] 
	public class Tab : AjaxControl
	{       
		#region Properties
		#region Selected
		private bool selected = false;
		/// <summary>
		/// Indicates if this tab is selected. TabSelected() will be called in the parent TabStrip if 
		/// this value is set to true. This gives it a chance.
		/// </summary>
		public bool Selected
		{
			get
			{
				return selected;
			}
			set
			{
                TabStrip ts = Parent as TabStrip;
				if (ts != null && value == true)
					ts.TabSelected(this);
				selected = value;
			}
		} 
		#endregion

		#region Title
		private string title = "";
		/// <summary>
		/// The Text to diplay in the title of the tab.
		/// </summary>
		public string Title
		{
			get { return title; }
			set { title = value; }
		} 
		#endregion

		#region DelayLoading
		/// <summary>
		/// Don't load the url until the Tab is selected.
		/// </summary>
        private bool delayLoading = true;
        public bool DelayLoading
        {
            get
            {
                return delayLoading;
            }
            set
            {
                delayLoading = value;
            }
        }
		#endregion
		

		#region Url
		/// <summary>
		/// The Url to request when the tab 
		/// </summary>
        private string url;
        public string Url
        {
            get 
            {
                string fullurl = url;
                string qs = QueryString;
                if (fullurl != null)
                {
                    if (qs != null)
                        fullurl += "?" + qs;
                }
                return fullurl;
            }
            set {url=value;}
        }
		#endregion

        #region QueryString
        /// <summary>
        /// The query string to append to the url
        /// </summary>
        private string queryString;
        public string QueryString
        {
            get { return queryString; }
            set { queryString = value; }
        }
        #endregion



		#region ContentLoadedFromUrl
		public bool ContentLoadedFromUrl
		{
			get
			{
				return Url != null && Url != "";
			}
		} 
		#endregion

		#region Target
		public enum TargetType
		{
			Top,
			Div,
			IFrame
		}
		public TargetType Target = TargetType.IFrame; 
		#endregion

		#region OnClick
		/// <summary>
		/// The javascript to execute when the Tab is clicked. This will be run after the javascript to make this tab visible.
		/// </summary>
        private string onClick;
        public string OnClick
        {
            get { return onClick; }
            set { onClick = value; }
        }
		#endregion

		#region Image
		/// <summary>
		/// The Url of an Image to display in the Tab
		/// </summary>
        public string Image
        {
            get;
            set;
        }
		#endregion

        private string padding="5px 5px 5px 5px";
        public string Padding
        {
            get { return padding; }
            set { padding = value; }
        }
		#endregion

        #region TitleTemplates
        /// <summary>
        /// The Html Template for the Tab Title
        /// Tokens:
        /// #CID# is the JavascriptId
        /// #CJS# is the on click javascript
        /// </summary>
        public static string Template3 = @"
<table cellpadding=""0"" cellspacing=""0"" >
	<tr>
		<td id=""#CID#_l"" class=""TabLeftSelected""><div style=""width:#WD#px;""></div></td>
		<td id=""#CID#"" class=""TabMiddleSelected"" onclick=""#CJS#"" >#IMG##TC#</td>
		<td id=""#CID#_r"" class=""TabRightSelected""><div style=""width:#WD#px;""></div></td>
	</tr>
</table>";               
		
		#endregion


		#region RenderTitle
		/// <summary>
		/// Called by the Tab Strip Control to generate the html for rendering the title for this tab. 
		/// </summary>
		/// <returns></returns>
		public virtual string RenderTitle()
		{
			StringBuilder html = null;
            switch (Configuration.Settings.Current.TabStrip.Template)
            {                
                default:
                    html = new StringBuilder(Template3);
                    break;
            }

            html.Replace("#WD#", Configuration.Settings.Current.TabStrip.LeftRightWidth.ToString());
            
			
			//SelectTab(TabId, TabStripObject, [Url], [FrameHeight]);
			string ClickScript = Parent.JavascriptId+".Select('" + JavascriptId+ "'";
			if (ContentLoadedFromUrl && DelayLoading)
			{
				ClickScript += (",'" + Url + "'");
			}
			ClickScript += (");" + OnClick);
			if (ContentLoadedFromUrl)
			{
				if(Target==TargetType.Top)
					ClickScript = "document.location.href='" + Url + "';";				
			}
			html.Replace("#CJS#",ClickScript);

			html.Replace("#TC#",Title);
			html.Replace("#CID#", JavascriptId);

            if (!Selected)
                html.Replace("Selected","");
            
            if(string.IsNullOrEmpty(Image))
				html.Replace("#IMG#", "");
			else
                html.Replace("#IMG#", "<img src=\"" + Resources.ImageUrl(Image) + "\" />&nbsp;");
			return html.ToString();
		} 
		#endregion        

        private Unit? height = null;
        public override Unit Height
        {
            get
            {
                if (height.HasValue)
                    return height.Value;
                if (Parent != null)
                    return Parent.Height;
                return base.Height;
            }
            set
            {
                height = value;
                base.Height = value;
            }
        }
		/*
        private Unit? minHeight = null;
        public Unit? MinHeight
        {
            get
            {
                if (minHeight.HasValue)
                    return minHeight.Value;
                if (Parent != null)
                    return Parent.MinHeight;
                return null;
            }
            set
            {
                minHeight = value;
            }
        }*/

        public new TabStrip Parent
        {
            get
            {
                return base.Parent as TabStrip;
            }
        }

        public string HeightStyleString
        {
            get
            {
				/*
                if (MinHeight != null)
                {
                    if(Parent.Browser == Browser.IE6)   //Use combination of Height and overflow to mimic min-height
                       return "height:" + MinHeight.ToString() + ";overflow:visible;";
                    return "min-height:" + MinHeight.ToString() + ";";
                }*/
                return "height:" + Height.ToString() + ";";
            }
        }

		#region Render
		/// <summary>
		/// Surrounds the Tab content with a Div which has the CssClass "TabContent"
		/// </summary>
		/// <param name="writer"></param>
		protected override void Render(HtmlTextWriter writer)
		{
			writer.Write("<div class=\"TabContent\" ");
            StringBuilder style = new StringBuilder("style=\""+HeightStyleString);
			if (!Selected)
				style.Append("display:none;");
            if(!string.IsNullOrEmpty(Padding)&&!ContentLoadedFromUrl)
                style.Append("padding:"+Padding+";");
            style.Append("\"");
            writer.Write(style);
			string id = JavascriptId + "_Content";
			writer.Write(" id=\"" + id + "\">");
			if (Target == TargetType.IFrame && ContentLoadedFromUrl)
			{
				string FrameId = JavascriptId + "_Frame";
                //writer.Write("<iframe style=\"overflow:visible;\" onload=\"ResizeIFrame(this);\" marginWidth=\"0\" marginHeight=\"0\"");
                writer.Write("<iframe marginWidth=\"0\" marginHeight=\"0\" ");
				if (ContentLoadedFromUrl && !DelayLoading)
					writer.Write("src=\"" + Url + "\"");
				writer.Write("width=\"100%\" height=\"100%\" frameBorder=\"0\" name=\"" + FrameId + "\" id=\"" + FrameId + "\" ></iframe>");
			}
			else
				base.Render(writer);
			writer.WriteLine("</div>");
			if (Target != TargetType.IFrame && ContentLoadedFromUrl)
				writer.WriteLine("<script type=\"text/javascript\" >new WebRequest('" + Url + "','" + id + "')</script>");
		}
		#endregion

        //Prevent the default begin and end tags from being rendered.
        public override void RenderBeginTag(HtmlTextWriter writer)
        {
        }

        public override void RenderEndTag(HtmlTextWriter writer)
        {
        }
	}
}
